// Copyright (c) 2014 Jonathan Magnan (http://jonathanmagnan.com/).
// All rights reserved (http://zzzproject.com/icon-library/).
// Licensed under MIT License (MIT) (https://ziconlibrary.codeplex.com/license).

// All icons are licensed under a Creative Commons Attribution 3.0 License.
// http://creativecommons.org/licenses/by/3.0/us/
// Copyright 2009-2013 FatCow Web Hosting. All rights reserved.
// http://www.fatcow.com/free-icons


using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Reflection;


public static partial class IconExtensions
{
    /// <summary>
    ///     An Icon extension method that get the Icon.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <returns>The Icon.</returns>
    public static System.Drawing.Icon GetIcon(this Z.IconLibrary.FarmFresh16.Icon @this)
    {
        Type enumType = typeof (Z.IconLibrary.FarmFresh16.Icon);
        Assembly assembly = enumType.Assembly;
        FieldInfo fi = enumType.GetField(@this.ToString());
        var attributes = (DescriptionAttribute[]) fi.GetCustomAttributes(typeof (DescriptionAttribute), false);

        if (attributes.Length > 0)
        {
            string path = attributes[0].Description;
            string assemblyResourceName = "Z.IconLibrary.FarmFresh16.Icon." + path;
            using (Stream stream = assembly.GetManifestResourceStream(assemblyResourceName))
            {
                if (stream != null)
                {
                    using (var bitmap = new Bitmap(stream))
                    {
                        IntPtr intPtr = bitmap.GetHicon();
                        using (var iconHandle = System.Drawing.Icon.FromHandle(intPtr))
                        {
                            var icon = new System.Drawing.Icon(iconHandle, iconHandle.Width, iconHandle.Height);
                            DestroyIcon(intPtr);
                            return icon;
                        }
                    }
                }
                else
                {
                    return null;
                }
            }
        }
        return null;
    }
}
